package com.gitee.cashzhang27.test.cloud.webflux.hi.controller;

import com.gitee.cashzhang27.test.cloud.webflux.hi.service.HttpBinService;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/11/26 10:32
 */
@Slf4j
@RestController
@AllArgsConstructor
public class CircuitBreakerController {

  private final ReactiveCircuitBreakerFactory circuitBreakerFactory;
  private final HttpBinService httpBin;

  @GetMapping("/get")
  public Mono<Map> get() {
    return httpBin.get();
  }

  @GetMapping("/delay/{seconds}")
  public Mono<Map> delay(@PathVariable int seconds) {
    return circuitBreakerFactory
        .create("delay")
        .run(
            httpBin.delay(seconds),
            t -> {
              log.warn("delay call failed error", t);
              Map<String, String> fallback = new HashMap<>();
              fallback.put("hello", "world");
              return Mono.just(fallback);
            });
  }

  @GetMapping("/flux-delay/{seconds}")
  public Flux<String> fluxDelay(@PathVariable int seconds) {
    return circuitBreakerFactory
        .create("delay")
        .run(
            httpBin.fluxDelay(seconds),
            t -> {
              log.warn("delay call failed error", t);
              return Flux.just("hello", "world");
            });
  }
}
